package com.liuqianfei.markme.rules.inline;

import com.liuqianfei.markme.rules.AbstractState;
import com.liuqianfei.markme.rules.IAction;
import com.liuqianfei.util.StringUtil;

/**
 * Skip text characters for text token, place those to pending buffer
 * and increment current pos
 *
 * @author liuqianfei
 */
public class TextAction implements IAction
{
    // Rule to skip pure text
    // '{}$%@~+=:' reserved for extentions

    // !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~

    // !!!! Don't confuse with "Markdown ASCII Punctuation" chars
    // http://spec.commonmark.org/0.15/#ascii-punctuation-character
    private boolean isTerminatorChar(char ch)
    {
        switch (ch)
        {
            case 0x0A/* \n */:
            case 0x21/* ! */:
            case 0x23/* # */:
            case 0x24/* $ */:
            case 0x25/* % */:
            case 0x26/* & */:
            case 0x2A/* * */:
            case 0x2B/* + */:
            case 0x2D/* - */:
            case 0x3A/* : */:
            case 0x3C/* < */:
            case 0x3D/* = */:
            case 0x3E/* > */:
            case 0x40/* @ */:
            case 0x5B/* [ */:
            case 0x5C/* \ */:
            case 0x5D/* ] */:
            case 0x5E/* ^ */:
            case 0x5F/* _ */:
            case 0x60/* ` */:
            case 0x7B/* { */:
            case 0x7D/* } */:
            case 0x7E/* ~ */:
                return true;
            default:
                return false;
        }
    }

    @Override
    public boolean parse(AbstractState state, boolean silent, int startLine, int endLine)
    {
        int pos = state.getPos();

        while (pos < state.getPosMax() && !isTerminatorChar(state.getSrc().charAt(pos)))
            pos++;

        if (pos == state.getPos())
            return false;

        if (!silent)
            state.setPending(state.getPending() + StringUtil.slice(state.getSrc(), state.getPos(), pos));

        state.setPos(pos);

        return true;
    }

    // Another memory implementation
}
